﻿using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc;
using Rw.Core.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WH.Common.Filter
{
    /// <summary>
    /// 
    /// </summary>
    public class ValidateModelFilter : IResultFilter
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        public void OnResultExecuted(ResultExecutedContext context)
        {
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        public void OnResultExecuting(ResultExecutingContext context)
        {
            if (!context.ModelState.IsValid)
            {

                var param = string.Join(',', context.ModelState.Keys);
                var msg = $"{param}参数验证失败，请检查";

                if (context.Result is BadRequestObjectResult res)
                {
                    var obj = res.Value as ValidationProblemDetails;
                    if (obj is not null)
                    {
                        msg = obj.Errors.Values.First().First();
                    }
                }

                var response = new ResultResponse
                {
                    Code = 400,
                    IsSucceed = false,
                    Msg = msg
                };

                context.HttpContext.Response.StatusCode = 400;

                var result = new JsonResult(null)
                {
                    Value = response
                };

                context.Result = result;
            }

            //if (context.Result is BadRequestObjectResult res)
            //{
            //    var obj = res.Value as ValidationProblemDetails;
            //    var errorMsg = obj.Errors.Values.First()[0];
            //    context.Result = new JsonResult(new ResultResponse() { Msg = errorMsg, IsSucceed = false });
            //    return;
            //}
        }
    }
}
